package com.laiyw.monitor.core.http;

import com.laiyw.monitor.utils.StreamUtils;
import com.laiyw.monitor.utils.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * 资源处理Servlet
 *
 * @Description:
 * @Auther: Laiyw
 * @Date: 2018/10/3 23:10
 */
public abstract class ResourceServlet extends HttpServlet {
    protected Logger logger = Logger.getLogger("ResourceServlet");

    protected final String resourcePath;

    public ResourceServlet(String resourcePath) {
        this.resourcePath = resourcePath;
    }

    protected String getFilePath(String fileName) {
        return resourcePath + fileName;
    }

    protected void returnResourceFile(String fileName, String uri, HttpServletResponse response)
            throws ServletException,
            IOException {
        String text = StreamUtils.readFromResource(getFilePath(fileName));
        if (text == null) {
            write(response);
        }
        if (fileName.endsWith(".css")) {
            response.setContentType("text/css;charset=utf-8");
        } else if (fileName.endsWith(".js")) {
            response.setContentType("text/javascript;charset=utf-8");
        }
        response.getWriter().write(text);
    }

    protected void write(HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.getWriter().write("无效的资源文件");
        return;
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");

        String contextPath = request.getContextPath();//web项目配置的context 例：/web
        String servletPath = request.getServletPath();//MonitorServlet url-pattern配置的路径 例：/monitor
        String requestURI = request.getRequestURI();//请求路径 例：/web/monitor/bootstrap/js/bootstrap.min.js

        if (null == contextPath) {
            contextPath = "";
        }
        String cspath = contextPath + servletPath;
        //本地文件路径或json请求 例:/bootstrap/js/bootstrap.min.js；cpu.html；disk.json
        String path = requestURI.substring(cspath.length());

        if ("".equals(path) || "/".equals(path)) {
            write(response);
        }

        if (path.indexOf(".json") >= 0) {
            String fullUrl = path;
            if (StringUtils.isNotEmpty(request.getQueryString())) {
                fullUrl += "?" + request.getQueryString();
            }
            response.setContentType("application/json");
            response.getWriter().print(process(fullUrl, request.getServletContext()));
            return;
        }

        returnResourceFile(path, cspath, response);
    }

    protected abstract String process(String url, ServletContext servletContext);
}

